let socketIo = {};
let socket_io = require('socket.io');
const { ChatRoomModel, UserchatModel, infoModel, userModel, InfoChatModel } = require("../db/index");
const cors = {
    origin: '*',
    methods: ["GET", "POST"]
};
socketIo = function (server) {
    let uses = {}; // 存储各个聊天室（或群聊）中的成员列表
    let s_rid = {}; // 映射用户的ID到他们的Socket.IO连接ID，用来追踪用户是否在线
    let io = socket_io(server, { cors: cors }); // 创建Socket.IO服务器实例，绑定到传入的HTTP服务器上
    io.on('connection', (socket) => {
        console.log('A user connected:', socket.id);
        socket.on("add_zaixian", async (from, callback) => { //在s_rids中添加socket.id的
            s_rid[from.from] = socket.id
            console.log(from.from, '撒发的');
            let uid = await userModel.findOne({ _id: from.from })
            let use = await userModel.findOne({ rid: from.from, cid: null })
            // if (!use) UserchatModel.create({ rid:from.from, cid: null, beizhu: "好友申请", info: [], avater: "" })
            callback(uid)
        })
        //用户进入群聊时执行一次
        socket.on('get_messages', async (data, callback) => {
            const { from, to } = data;  //发送者from,接收的消息的群聊to
            console.log(from, to, '进入群聊');
            console.log(uses, '群聊123456789');
            try {
                if (uses[to]) { //看这个群聊有没有连接到scoket.io
                    uses[to].includes(from) ? '' : uses[to].push(from)//看有没有在这个房间
                } else {
                    uses[to] = [from] //如果没有这个群聊房间就加上,并且加入
                }
                console.log(uses, '群聊11111111111119');
                console.log(s_rid, 123456789);
                console.log(s_rid[from], 123456789111111);
                const messages = await UserchatModel.findOne({ rid: from, cid: to }).populate('cid') //找到我的这个群聊
                //修改我访问这个群聊的最新时间
                await UserchatModel.updateOne({ _id: messages._id }, { access_time: Date.now() })
                // console.log(messages);
                // 如果有 info 数据，则为每个 info 项添加 img 字段
                if (messages && messages.info && messages.info.length > 0) {
                    // 创建一个映射函数来添加 img 字段
                    const fetchImages = messages.info.map(async item => {
                        const user = await userModel.findById(item.uid).select('img');
                        return { ...item.toObject(), img: user ? user.img : null };
                    });

                    // 使用 Promise.all 来等待所有图片数据加载完成
                    messages.info = await Promise.all(fetchImages);
                }
                callback(
                    {
                        id: messages._id,
                        xinxi: messages?.info,
                        name: messages.beizhu || messages.cid?.name
                    }
                ); //获得我在这个群聊的信息
            } catch (err) {
                callback({ err: err.message })
            }
        });
        //用户发送
        socket.on('send', async (info) => {
            let { use, id, message, img, name } = info //use:群id,id:用户id,message:发送内容
            console.log(use, id, message, img, name, 123456789);

            let list = await ChatRoomModel.findOne({ _id: use }) //找到这个群聊
            let zaixain = uses[use] || [] //获取在线的ssockid
            console.log(uses);
            console.log(zaixain, '在线的ssockid');
            console.log(list.name);

            let create = Date.now()
            if (list?.rids.length === 1) {
                io.to(s_rid[id]).emit('receive', { message: "被删除了,对方接收不到" })
                return
            }
            if (id && !list?.rids.includes(id)) {
                io.to(s_rid[id]).emit('receive', { message: "您已被移除了群聊" })
                return
            }
            console.log(message, '啊大公司方大化工');

            list?.rids.forEach(async (item) => {
                let rid = JSON.parse(JSON.stringify(item))
                await UserchatModel.updateOne(
                    { rid: rid, cid: use },
                    {
                        $push:
                        {
                            info: {
                                uid: id,
                                content: message,
                                img: img,
                                name: name,
                                isread: zaixain.includes(rid),
                                create_time: create
                            }
                        }
                    }
                )//给这个群聊关联的用户群聊信息表添加新消息
                if (zaixain.includes(rid)) {  //如果在zaixain中说明这个rid在这个房间中
                    console.log({ message: message, id: id, name: name, img: img, create });
                    io.to(s_rid[rid]).emit('receive', { message: message, id: id, name: name, img: img, create })//发送给这个房间的所有人
                    console.log('12345676543234565432');

                } else if (s_rid[rid]) {  //没子啊zaixain中说明这个rid离开了房间
                    io.to(s_rid[rid]).emit('weidu', { cid: use })
                }
            })
        })
        // 用户进入一对一页面执行
        socket.on('get_infochat', async (data, callback) => {
            const { from, to } = data;  //我from,他to我的id和别人的id
            console.log(from, to, '一对一');
            try {
                // 检查双方是否都在线
                if (s_rid[from] && s_rid[to]) {
                    // 获取历史消息
                    const history = await InfoChatModel.findOne({ $or: [{ myid: from, youid: to }, { myid: to, youid: from }] }).populate('youid');
                    console.log(history, '历史消息');
                    console.log(s_rid, 123456789);
                    console.log("form:", s_rid[from], "to:", s_rid[to]);
                    callback({
                        content: history?.content || [],
                    });
                } else {
                    callback({ error: '一方不在线' });
                }
            } catch (err) {
                callback({ error: err.message });
            }
        })
        socket.on('infosend', async (data, callback) => {
            const { message, myid, youid } = data;
            console.log(message, myid, youid, '发送一对一消息');
            try {
                // 找到或创建一对一聊天记录
                let chat = await InfoChatModel.findOne({ $or: [{ myid: myid, youid: youid }, { myid: youid, youid: myid }] });
                if (!chat) {
                    chat = await InfoChatModel.create({ myid: myid, youid: youid,content: [] });
                }
                 const mydata = await userModel.findById(myid);
                 console.log(mydata,123456789);
                // 添加新消息
                const newMessage = {
                    uid: myid,
                    content: message,
                    create_time: Date.now(),
                    img: mydata?.img,
                };
                await InfoChatModel.updateOne({ _id: chat._id }, { $push: { content: newMessage } });

                // 发送消息给对方
                if (s_rid[youid]) {
                    io.to(s_rid[youid]).emit('inforeceive', newMessage);
                }
                console.log('发送成功');
                // 确认消息发送成功
                callback(null);
            } catch (err) {
                callback({ err: err.message });
            }
        });
    })
}
